package com.glasses.business.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.test.espresso.core.deps.guava.eventbus.Subscribe;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.facebook.drawee.view.SimpleDraweeView;
import com.glasses.business.R;
import com.glasses.business.adapter.OrderGoodsAdapter;
import com.glasses.business.entity.CheckMenu;
import com.glasses.business.entity.OrderDetail;
import com.glasses.business.entity.OrderList;
import com.glasses.business.entity.PayInfo;
import com.glasses.business.event.BussEvent;
import com.glasses.business.http.NetUtils;
import com.glasses.business.utils.Tools;

import net.neiquan.okhttp.NetCallBack;
import net.neiquan.okhttp.ResultModel;

import org.haitao.common.utils.AppLog;
import org.haitao.common.utils.ToastUtil;
import org.json.JSONException;
import org.json.JSONObject;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;

/**
 * Author：邓勇军
 * English Name：Deng,The Sky Fucker!
 * Email：dandycoder@126.com
 * Date：2017/3/9
 * Version：1.0
 */

public class OrderDetailActivity extends Activity {
    @InjectView(R.id.orderNum)
    TextView orderNum;
    @InjectView(R.id.wlNum)
    TextView wlNum;
    @InjectView(R.id.orderDetailName)
    TextView orderDetailName;
    @InjectView(R.id.orderDetailPhone)
    TextView orderDetailPhone;
    @InjectView(R.id.orderDetailAddr)
    TextView orderDetailAddr;
    @InjectView(R.id.orderDetailRecylerView)
    RecyclerView orderDetailRecylerView;
    @InjectView(R.id.cancelTv)
    TextView cancelTv;
    @InjectView(R.id.payTv)
    TextView payTv;
    @InjectView(R.id.title_tv)
    TextView titleTv;
    @InjectView(R.id.back_img)
    ImageView backImg;
    @InjectView(R.id.orderScrollView)
    ScrollView orderScrollView;
    @InjectView(R.id.totalMoney)
    TextView totalMoney;
    @InjectView(R.id.actualMoney)
    TextView actualMoney;
    @InjectView(R.id.orderTime)
    TextView orderTime;
    @InjectView(R.id.orderStatus)
    TextView orderStatus;
    @InjectView(R.id.leftSPH)
    TextView leftSPH;
    @InjectView(R.id.leftCYL)
    TextView leftCYL;
    @InjectView(R.id.leftAXL)
    TextView leftAXL;
    @InjectView(R.id.rightSPH)
    TextView rightSPH;
    @InjectView(R.id.rightCYL)
    TextView rightCYL;
    @InjectView(R.id.rightAXL)
    TextView rightAXL;
    @InjectView(R.id.eyesPD)
    TextView eyesPD;
    @InjectView(R.id.lightOrderLL)
    LinearLayout lightOrderLL;
    @InjectView(R.id.lightImg)
    SimpleDraweeView lightImg;
    @InjectView(R.id.lightImgLL)
    LinearLayout lightImgLL;
    private int id;
    private OrderGoodsAdapter adapter;
    private int status;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
//                WindowManager.LayoutParams.FLAG_FULLSCREEN);  //全屏
        setContentView(R.layout.fragment_order_detail);
        ButterKnife.inject(this);
        titleTv.setVisibility(View.VISIBLE);
        titleTv.setText("订单详情");
        StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(1,
                StaggeredGridLayoutManager.VERTICAL);
        layoutManager.setOrientation(StaggeredGridLayoutManager.VERTICAL);
        orderDetailRecylerView.setLayoutManager(layoutManager);
        adapter = new OrderGoodsAdapter(this, null);
        orderDetailRecylerView.setAdapter(adapter);
        orderDetailRecylerView.addItemDecoration(new SpaceItemDecoration(2));
        orderScrollView.scrollTo(0, 0);
        if (getIntent() != null) {
            id = getIntent().getIntExtra("id", 0);
            Tools.showDialog(this);
            NetUtils.getInstance().orderDetail(id, new NetCallBack() {

                @Override
                public void onSuccess(String response, String mssage, ResultModel model) {
                    Tools.dismissWaitDialog();
                    ToastUtil.shortShowToast(mssage);
                    final OrderDetail orderDetail = (OrderDetail) model.getModel();
                    if (orderDetail != null) {
                        orderNum.setText("订单号：" + orderDetail.getOrderNO());
                        String transNO = orderDetail.getTransNO();
                        if (!TextUtils.isEmpty(transNO)) {
                            wlNum.setText("顺丰快递单号：" + transNO);
                        } else {
                            wlNum.setText("顺丰快递单号：暂无");
                        }
                        OrderDetail.ReceiverBean receiver = orderDetail.getReceiver();
                        if (receiver != null) {
                            orderDetailName.setText(receiver.getReceiver());
                            orderDetailPhone.setText(receiver.getPhone());
                            orderDetailAddr.setText(receiver.getAddress());
                        }
                        totalMoney.setText("￥" + orderDetail.getTotalPrice());
                        actualMoney.setText("￥" + orderDetail.getFianlPrice());
                        orderTime.setText("￥" + orderDetail.getTime());
                        adapter.appendAll(orderDetail.getProductList());
                        OrderDetail.CheckMenuBean checkMenu = orderDetail.getCheckMenu();
                        if (checkMenu != null) {
                            switch (checkMenu.getType()) {
                                case 0:
                                    lightOrderLL.setVisibility(View.VISIBLE);
                                    lightImgLL.setVisibility(View.GONE);
                                    CheckMenu data = JSON.parseObject(checkMenu.getContent(), CheckMenu.class);
                                    leftSPH.setText(data.getLeftSPH());
                                    leftAXL.setText(data.getLeftAXL());
                                    leftCYL.setText(data.getLeftCYL());
                                    rightSPH.setText(data.getRightSPH());
                                    rightAXL.setText(data.getRightAXL());
                                    rightCYL.setText(data.getRightCYL());
                                    eyesPD.setText(data.getEyesPD());
                                    break;
                                case 1:
                                    lightOrderLL.setVisibility(View.GONE);
                                    lightImgLL.setVisibility(View.VISIBLE);
                                    String imgPath = null;
                                    try {
                                        imgPath = new JSONObject(checkMenu.getContent()).getString("imgPath");
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                    lightImg.setImageURI(imgPath);
                                    break;
                            }
                        }
                        status = orderDetail.getStatus();
                        switch (status) {
                            case 1:
                                orderStatus.setText("待付款");
                                cancelTv.setVisibility(View.VISIBLE);
                                payTv.setVisibility(View.VISIBLE);
                                cancelTv.setText("取消订单");
                                payTv.setText("付款");
                                cancelTv.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View view) {
                                        cancelDel(0, orderDetail);
                                    }
                                });
                                payTv.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View view) {
                                        pay();
                                    }
                                });
                                break;
                            case 2:
                                orderStatus.setText("待收货");
                                cancelTv.setVisibility(View.GONE);
                                payTv.setVisibility(View.VISIBLE);
                                payTv.setText("确认收货");
                                payTv.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View view) {
                                        sureReceiver(orderDetail);
                                    }
                                });
                                break;
                            case 3:
                                orderStatus.setText("已完成");
                                cancelTv.setVisibility(View.VISIBLE);
                                payTv.setVisibility(View.VISIBLE);
                                cancelTv.setText("申请售后");
                                payTv.setText("删除订单");
                                cancelTv.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View view) {
                                        if(System.currentTimeMillis()<orderDetail.getCanApplyRefendTime()) {
                                            cancelDel(1, orderDetail);
                                        }else{
                                            ToastUtil.shortShowToast("退货时间已过...");
                                        }
                                    }
                                });
                                payTv.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View view) {
                                        cancelDel(2, orderDetail);
                                    }
                                });
                                break;
                            case 4:
                                orderStatus.setText("售后中");
                                cancelTv.setVisibility(View.GONE);
                                payTv.setVisibility(View.GONE);
                                break;
                            case 5:
                                orderStatus.setText("售后完成");
                                cancelTv.setVisibility(View.GONE);
                                payTv.setVisibility(View.VISIBLE);
                                payTv.setText("删除订单");
                                payTv.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View view) {
                                        cancelDel(2, orderDetail);
                                    }
                                });
                                break;
                        }
                    }
                }

                @Override
                public void onFail(boolean dataError, int errorCode, String mssage) {
                    Tools.dismissWaitDialog();
                    ToastUtil.shortShowToast(mssage);
                }
            }, OrderDetail.class);
        }
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    @Subscribe
    public void onEventMainThread(BussEvent event) {
        if (event.getState() == BussEvent.Order_Refush) {
            finish();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @OnClick({R.id.back_img})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.back_img:
                finish();
                break;
        }
    }

    private void pay() {
        Tools.showDialog(this);
        NetUtils.getInstance().payInformation(id, new NetCallBack() {
            @Override
            public void onSuccess(String response, String mssage, ResultModel model) {
                Tools.dismissWaitDialog();
                ToastUtil.shortShowToast(mssage);
                PayInfo payInfo = (PayInfo) model.getModel();
                switch (payInfo.getIsHaveProduct0Information()) {
                    case 0:
                        Intent intent1 = new Intent(OrderDetailActivity.this, OrderCompanyActivity.class);
                        intent1.putExtra("payMoney", payInfo);
                        startActivity(intent1);
                        break;
                    case 1:
                        Intent intent = new Intent(OrderDetailActivity.this, PayActivity.class);
                        intent.putExtra("payMoney", payInfo);
                        startActivity(intent);
                        break;
                    default:
                        break;
                }
            }

            @Override
            public void onFail(boolean dataError, int errorCode, String mssage) {
                Tools.dismissWaitDialog();
                ToastUtil.shortShowToast(mssage);
            }
        }, PayInfo.class);
    }

    private void cancelDel(final int flag, final OrderDetail orderList) {
        String title = null;
        switch (flag) {
            case 0:
                title = "确认取消该订单?";
                break;
            case 1:
                title = "确认售后?";
                break;
            case 2:
                title = "确认删除该订单?";
                break;
        }
        new AlertDialog.Builder(this).setMessage(title)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.dismiss();
                        switch (flag) {
                            case 0://取消订单
                                cancelOrder(orderList);
                                break;
                            case 1://售后
                                Intent intent = new Intent(OrderDetailActivity.this, BackMoneyActivity.class);
                                intent.putExtra("id",orderList.getId());
                                startActivity(intent);
                                break;
                            case 2://删除订单
                                cancelOrder(orderList);
                                break;
                        }
                    }
                }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                dialogInterface.dismiss();
            }
        }).create().show();
    }

    private void sureReceiver(OrderDetail orderList) {
        Tools.showDialog(this);
        NetUtils.getInstance().sureReceive(orderList.getId(), new NetCallBack() {
            @Override
            public void onSuccess(String response, String mssage, ResultModel model) {
                Tools.dismissWaitDialog();
                ToastUtil.shortShowToast(mssage);
                EventBus.getDefault().post(new BussEvent(BussEvent.Order_Refush));
                finish();
            }

            @Override
            public void onFail(boolean dataError, int errorCode, String mssage) {
                Tools.dismissWaitDialog();
                ToastUtil.shortShowToast(mssage);
            }
        }, null);
    }

    private void cancelOrder(OrderDetail orderList) {
        Tools.showDialog(this);
        NetUtils.getInstance().cancelOrder(orderList.getId(), new NetCallBack() {
            @Override
            public void onSuccess(String response, String mssage, ResultModel model) {
                Tools.dismissWaitDialog();
                ToastUtil.shortShowToast(mssage);
                EventBus.getDefault().post(new BussEvent(BussEvent.Order_Refush));
                finish();
            }

            @Override
            public void onFail(boolean dataError, int errorCode, String mssage) {
                Tools.dismissWaitDialog();
                ToastUtil.shortShowToast(mssage);
            }
        }, null);
    }


    public class SpaceItemDecoration extends RecyclerView.ItemDecoration {

        private int space;

        public SpaceItemDecoration(int space) {
            this.space = space;
        }

        @Override
        public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {

            if (parent.getChildPosition(view) != 0) {
                outRect.bottom = space;
                outRect.top = space;
            }
        }
    }
}
